<template>
	<view>
		<dev-navbar :title="title"></dev-navbar>

		<view class="measurement-time-box justify-content-l" v-if="measurementItem.itemCode !=='SLEEP'">
			<view class="measurement-type">
				测量时间
			</view>
			<view class="align-items-l">
				<!-- :hide-second="true" -->
				<uni-datetime-picker :value="currentTime" :end="currentTime" @change="clickTime" type="datetime">
					<text class="time-text">
						{{createTime}}
					</text>
				</uni-datetime-picker>
				<dev-svg-image height="32"></dev-svg-image>
			</view>
		</view>
		<view v-if="measurementItem.itemCode ==='BLOOD_SUGAR'" class="measurement-time-box justify-content-l">
			<view class="measurement-type">
				测量时间段
			</view>
			<view class="align-items-l">
				<text class="time-text" @tap="timePeriodPopup=true">
					{{selectTimeSlot.label}}
				</text>
				<dev-svg-image height="32"></dev-svg-image>
			</view>
		</view>
		<view class="data-title">
			{{measurementItem.indicName || ''}}
		</view>

		<view class="data-selection-box" v-if="measurementItem.itemCode=='BLOOD_PRESSURE'">
			<view class="" v-if="item.keyDesc!=='心率'" v-for="(item,index) in dataField" :key="index">
				<view class="">
					<view class="">
						<text class="small-name">{{item.keyDesc}}</text>
						<text class="big-name">{{healthData[item.key]}}</text>
						<text class="small-name">{{item.unit}}</text>
					</view>
					<view style="margin-top: 20rpx;">
						<dev-ruler :decimal="item.type*1" :itemCode="moveDataJudge(item.keyDesc,healthData[item.key])"  :min-num="item.min*1" :max-num="item.max*1"
							v-model="healthData[item.key]" :initialValue="item.standard" ></dev-ruler>
					</view>
				</view>
				<dev-split-line v-show="index<1" bgColor="#F5F5F5" top="56" bottom="50"></dev-split-line>
			</view>
		</view>

		<view class="data-selection-box"
			v-if="measurementItem.itemCode!=='BLOOD_PRESSURE' && measurementItem.itemCode!=='SLEEP'">
			<view class="" v-for="(item,index) in dataField" :key="index">
				<view class="">
					<view class="">
						<text class="small-name">{{item.keyDesc}}</text>
						<text class="big-name">{{healthData[item.key]}}</text>
						<text class="small-name">{{item.unit}}</text>
					</view>
					<view style="margin-top: 20rpx;">
						<dev-ruler :decimal="item.type*1" :min-num="item.min*1" :max-num="item.max*1"
							v-model="healthData[item.key]" :initialValue="item.standard"></dev-ruler>
					</view>
				</view>
				<dev-split-line v-show="index!==dataField.length-1" bgColor="#F5F5F5" top="56" bottom="50">
				</dev-split-line>
			</view>
		</view>
		<view v-if="measurementItem.itemCode=='BLOOD_PRESSURE'">
			<view class="data-title">
				心率
				<dev-svg-image @tap="displayHeartRate()" v-if="isHeartRate" mode="image"
					image-url="shoppingMall/01695B6103914A56979EE71E132D91F1.png" :width="60" :height="60"></dev-svg-image>
				<dev-svg-image @tap="displayHeartRate()" v-else mode="image"
					image-url="shoppingMall/720E0E6813AD4F8D878D0180E35338FC.png" :width="60" :height="60">
				</dev-svg-image>
			</view>
			<view class="data-selection-box" v-if="isHeartRate">

				<view class="" v-show="dataField[2].keyDesc=='心率'" >

                    <view class="">
						<text class="small-name">{{dataField[2].keyDesc}}</text>
						<text class="big-name">{{heartRate}}</text>
						<text class="small-name">{{dataField[2].unit}}</text>
					</view>
					<view style="margin-top: 20rpx;">
						<dev-ruler :decimal="dataField[2].type*1" :min-num="dataField[2].min*1" :max-num="dataField[2].max*1"
							v-model="heartRate" :initialValue="dataField[2].standard"></dev-ruler>
					</view>
				</view>
			</view>
		</view>

		<view class="" v-if="measurementItem.itemCode=='SLEEP'">
			<view class="measurement-time-box justify-content-l">
				<view class="measurement-type">
					睡觉时间
				</view>
				<view class="align-items-l" @tap="displayTimeSelection(1)">
					<text class="time-text">
						{{startTime || '请选择'}}
					</text>
					<dev-svg-image height="32"></dev-svg-image>
				</view>
			</view>

			<view class="measurement-time-box justify-content-l">
				<view class="measurement-type">
					起床时间
				</view>
				<view class="align-items-l" @tap="displayTimeSelection(2)">
					<text class="time-text">
						{{endTime || '请选择'}}
					</text>
					<dev-svg-image height="32"></dev-svg-image>
				</view>
			</view>
		</view>



		<view class="data-title" v-if="measurementItem.indicName=='血压'">
			测量状态
		</view>
		<view class="measurement-status" v-if="measurementItem.indicName=='血压'">
			<view class="every-button" v-for="(item,index) in statusList" :key="index">
				<dev-button @tapDev="selectionStatus(item,index)" :bgColor="item.selectFlag==1?'#2EA7E0':'#E2E1E2'"
					width="160">{{item.measureStatusName}}</dev-button>
			</view>
			<view class="every-button">
				<dev-button @tapDev="showCustomPopUps()" width="160" mode="hollowed" borderColor="#E2E1E2"
					bgColor="#FFFFFF" color="#9B9B9B">+自定义
				</dev-button>
			</view>
			<view style="width: 160rpx;"></view>
			<view style="width: 160rpx;"></view>
		</view>

		<dev-button @tapDev="submitData()" width="708" height="90" radius="42" fontSize="34" top="36" left="20"
			bottom="50">确定</dev-button>

		<dev-iphone-bottom></dev-iphone-bottom>


		<u-modal show-cancel-button v-model="show" @confirm="clickSave()" :show-title="false">
			<view class="slot-content">
				<view class="custom">
					自定义
				</view>
				<input type="text" maxlength="4" v-model="measureStatusName" class="input-boxs-num">
			</view>
		</u-modal>

		<u-select v-model="timePeriodPopup" @confirm="selectTimePeriod" :list="list" title="请选择" cancel-color="#2EA7E0"
			confirm-color="#2EA7E0"></u-select>

		<u-popup border-radius="30" v-model="timeShow" mode="bottom">
			<view v-if="selectStartTime">
				<view class="selector-box">
					<view class="cancel" @tap="timeShow = false">
						取消
					</view>
					<view class="determine" @tap="clickOk">
						确定
					</view>
				</view>
				<dev-picker-time format="YYYY-MM-DD HH:mm:ss" :start-time="selectStartTime" :params="params"
					height="500" v-model="chooseTime"></dev-picker-time>
			</view>
		</u-popup>


	</view>
</template>

<script>
	import dayjs from '@/common/utils/day/day.js'
	import devRuler from '@/pagesHome/components/dev-ruler.vue'
	import uniDatetimePicker from '@/pagesHome/components/uni-datetime-picker/uni-datetime-picker.vue'
	
import uPopup from "@/uview-ui/components/u-popup/u-popup.vue"
import uModal from "@/uview-ui/components/u-modal/u-modal.vue"
import uSelect from "@/uview-ui/components/u-select/u-select.vue"
	export default {
		components: {
			devRuler,
			uniDatetimePicker,
			uModal,
			uSelect,
			uPopup,
		},
		data() {
			return {
				loading:false,//接口是否在请求中
				title: '记录',
				systolicPressure: 20, //收缩压
				diastolicPressure: 20, //收缩压
				isHeartRate: false, //是否测量心率
				show: false, //是否显示弹框
                heartRate:'',
				params: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: false
				},

				currentTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
				createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), //记录时间

				measureStatusName: '', //测量状态名称

				measurementItem: {

				}, //当前测量项

				dataField: [], //尺子数据

				healthData: {}, //正常值

				statusList: [], //测量列表

				list: [{
						value: '1',
						label: '空腹'
					},
					{
						value: '2',
						label: '早餐后'
					},
					{
						value: '3',
						label: '午餐前'
					},
					{
						value: '4',
						label: '午餐后'
					},
					{
						value: '5',
						label: '晚餐前'
					},
					{
						value: '6',
						label: '晚餐后'
					},
					{
						value: '7',
						label: '凌晨'
					}
				],
				timePeriodPopup: false, //时间段
				selectTimeSlot: {
					value: '1',
					label: '空腹'
				},
				timeSlot: '1', //时间段信息
				timeShow: false, //时间选择
				selectStartTime: '', //选择开始时间
				startTime: '', //开始时间
				endTime: '', //选择的时间
				chooseTime: '', //选择的时间
				chooseType: 1, //当前选择的时间类型 1 是开始时间 2 是结束时间

			};
		},
		onLoad(e) {
            uni.removeStorage({key:'d',success: function(res){}})
            uni.removeStorage({key:'h',success: function(res){}})
			this.selectStartTime = dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss');
			this.measurementItem = JSON.parse(e.data);
			console.log(this.measurementItem, 'this.measurementItem');
			this.dataField = JSON.parse(this.measurementItem.dataField)
			console.log(this.dataField, 'this.dataField');
			this.title = '记录' + this.measurementItem.indicName
			this.getMeasurementStatus(); //获取测量列表
		},
		methods: {
            moveDataJudge(descp,data){
               return descp+"-"+data
            },
			//选择时间
			clickOk() {
				if (this.chooseType == 1) {
					this.startTime = this.chooseTime;
					this.timeShow = false;
				} else {
					this.endTime = this.chooseTime;
					this.timeShow = false;
				}
			},
			//点击显示时间选择器
			displayTimeSelection(val) {
				this.chooseType = val;
				this.timeShow = true;
			},
			//选择时间段
			selectTimePeriod(val) {
				this.selectTimeSlot = val[0];
				this.timeSlot = val[0].value;
			},

			//修改刻度数据
			changeNum(val, key) {
				console.log(val)
				this.healthData[key] = val;
			},
			//新增测量状态
			clickSave() {
				if (!this.measureStatusName.trim() ) {
					this.$message.info('请输入状态名称')
					return
				}
				this.addMeasurementStatus();
				this.show = false;
			},
			//选择的时间信息
			clickTime(e) {
				this.createTime = e;
			},
			//显示心率
			displayHeartRate() {
				this.isHeartRate = !this.isHeartRate;
			},
			//添加测量状态
			addMeasurementStatus() {
				this.$https.post(global.apiUrls.addMeasurementStatus, {
					indicId: this.measurementItem.indicId,
					measureStatusName: this.measureStatusName, //测量状态名称
				}).then(res => {
					if (res.data.code == 1000) {
						this.statusList.push(res.data.result);
						this.$message.info('添加成功')
					}
				})
			},
			//显示自定义弹框
			showCustomPopUps() {
				this.show = !this.show;
			},
			//获取测量状态
			getMeasurementStatus() {
				this.$https.get(global.apiUrls.getMeasurementStatus, {
					indicId: this.measurementItem.indicId,
				}).then(res => {
					if (res.data.code == 1000) {
						this.statusList = res.data.result;
					}
				})
			},
			//选择状态
			selectionStatus(item, index) {
				if(item.measureStatusName ==='无活动'){
					this.statusList.forEach((v,i)=>{
							v.selectFlag = 0;
					})
				}else{
					this.statusList.forEach((v,i)=>{
						if(v.measureStatusName === '无活动'){
							v.selectFlag = 0;
						}
					})
				}
				this.statusList[index].selectFlag = item.selectFlag == 1 ? 0 : 1;
			},

			//提交数据
			submitData() {
				let measureStatusIds = [];
				this.statusList.forEach(item => {
					if (item.selectFlag == 1) {
						measureStatusIds.push(item.measureStatusId)
					}
				})
				if (this.measurementItem.itemCode == 'SLEEP') {
					if (this.startTime && this.endTime) {
						if (!dayjs(this.startTime).isBefore(this.endTime)) {
							this.$message.info('睡眠时间不能晚于起床时间')
							return
						}
						let d1 = new Date(this.startTime.replace(/-/g,'/'));
						let d2 = new Date(this.endTime.replace(/-/g,'/'));
						console.log(parseInt(d2 - d1));//两个时间相差的毫秒数
						console.log(parseInt(d2 - d1) / 1000,'秒');//两个时间相差的秒数
						console.log(parseInt(d2 - d1) / 60000,'分钟');//两个时间相差的分钟数
						console.log(parseInt(d2 - d1) / 3600000,'小时');//两个时间相差的小时数
						// return
						let formatMsgTime = (parseInt(d2 - d1) / 60000).toFixed();
						let userInfoKey = global.IS_DEV?'USER_DATA_BSY_T':'USER_DATA_BSY_Z';
						let fdata = {
							deviceType: 'SLEEP',
							recordTime: this.$basejs.getToday().join('-'),
							inputType: 1, //1手动 2设备
							userId: uni.getStorageSync(userInfoKey).userId,
							mac: '', //设备mac
							deviceId: '', //设备id
							healthDataId: '',
							healthData: JSON.stringify({
								sleepTimeLen: formatMsgTime
							}),
							measureStatusIds: measureStatusIds.toString(),
						}
						if(this.loading) return
						this.loading = true;
						this.$api.post(global.apiUrls.addRecord, fdata).then(res => {
							this.loading = false;
							if (res.data.code == 1000) {
								if (this.measurementItem.taskLibraryType) {
									let pages = getCurrentPages(); //当前页面栈
									let beforePage = pages[pages.length - 2]; //指定调用页面为上个页面
									beforePage.$vm.punchTheClock() //getData 是你要调用上个页面的方法，微信小程序不需要用 $vm
								}
								this.$message.info('提交成功')
								uni.navigateBack({
									delta: 1
								});
							} else {
								uni.showToast({
									title: res.data.message,
									icon: "none",
									duration: 2000
								});
							}
						}).catch(err => {})
					} else {
						this.$message.info('请先完善睡眠区间')
					}

				} else {
                    if(this.heartRate){
                        this.healthData.heartRate = this.heartRate
                    }
                    if(this.measurementItem.itemCode == 'BLOOD_PRESSURE'){
                        let bloodPressure  = this.healthData;
                        let systolicPre =  bloodPressure.systolicPre;
                        let diastolicPre =  bloodPressure.diastolicPre;
                        if(parseInt(diastolicPre)>parseInt(systolicPre)){
                            uni.showToast({
                            	title: '舒张压不能大于收缩压',
                            	icon:'none',
                            	duration: 2000
                            });
                            return;
                        }
                    }

					this.$https.post(global.apiUrls.indicatorDataRecord, {
						createTime: this.createTime,
						healthData: JSON.stringify(this.healthData),
						inputType: 1,
						recordTime: this.createTime,
						deviceType: this.measurementItem.itemCode,
						measureStatusIds: measureStatusIds.toString(),
						timeSlot: this.measurementItem.itemCode === 'BLOOD_SUGAR' ? this.timeSlot : 0
					}).then(res => {
						if (res.data.code == 1000) {
							// 如果存在 taskLibraryType 这个值，代表是从任务过来的，在保存成功后，调用任务打卡。
							if (this.measurementItem.taskLibraryType) {
								let pages = getCurrentPages(); //当前页面栈
								let beforePage = pages[pages.length - 2]; //指定调用页面为上个页面
								beforePage.$vm.punchTheClock() //getData 是你要调用上个页面的方法，微信小程序不需要用 $vm
							}
							this.$message.info('提交成功')
							uni.navigateBack({
								delta: 1
							});
						}
					})
				}


			}



		}

	}
</script>

<style lang="scss">
	.slot-content {
		padding: 30rpx 40rpx;

		.custom {
			font-size: 36rpx;
			font-weight: 400;
			color: #000000;
			margin-bottom: 40rpx;
		}

		.input-boxs-num {
			width: 100%;
			box-sizing: border-box;
			// width:460rpx;
			height: 56rpx;
			border: 1rpx solid #979797;
			border-radius: 22rpx;
			padding: 10rpx;
			font-size: 24rpx;
			font-weight: 400;
			color: #9B9B9B;
		}
	}


	.measurement-time-box {
		height: 102rpx;
		background-color: #fff;
		padding: 0rpx 24rpx;

		.measurement-type {
			font-size: 28rpx;
			font-weight: 500;
			color: #333333;
		}

		.time-text {
			font-size: 28rpx;
			font-weight: 400;
			color: #9B9B9B;
		}

	}

	.data-title {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 108rpx;
		padding: 0rpx 24rpx;
		font-size: 38rpx;
		font-weight: 500;
		color: #000000;
	}

	.measurement-status {
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex-wrap: wrap;
		padding: 15rpx 24rpx 0rpx;
		background-color: #fff;

		.every-button {
			margin-bottom: 20rpx;
		}
	}

	.data-selection-box {
		padding: 45rpx 46rpx;
		background-color: #fff;
		text-align: center;

		.small-name {
			font-size: 28rpx;
			font-weight: 400;
			color: #000000;
		}

		.big-name {
			font-size: 58rpx;
			font-weight: 500;
			color: #000000;
			margin: 0rpx 10rpx;
		}

	}

	.selector-box {
		padding: 30rpx 50rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.cancel {
			font-size: 30rpx;
			font-weight: 400;
			color: #999999;
		}

		.determine {
			font-size: 30rpx;
			font-weight: 400;
			color: #2EA7E0;
		}
	}
</style>
